/*
 * @Description: 单位管理上下文
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-05-26 17:00:22
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { message } from 'antd';
import { deleteUnit, editUnit, addUnit, fetchUnitByPage } from '@/api/units';
import {
  ADD_UNIT,
  DELETE_UNIT,
  EDIT_UNIT,
  HIDE_LOADING,
  LOADING,
  SET_QUERY,
  SET_SELECTED_ITEM,
  SET_UNITS_LIST,
  SWITCH_TABLE_TYPE
} from '../constants';
import { UnitReducer } from '../reducers/UnitReducer';
import { delItemByIdArray, editItemById, insertItem } from '@/utils/list';
import { appActions, appState } from '@/store/mobx';

const initialState = {
  // 列表相关
  listQuery: {
    pageNo: 1,
    pageSize: 10,
    param: {
      code: '',
      name: ''
    }
  },
  loading: false,
  // 表格展示形式，1-树结构，2-普通表格
  listType: 1,
  list: [],
  // 选中的表格条目
  selectItems: [],

  // filter 相关 list
  stateList: [
    { id: 0, name: '正常' },
    { id: 1, name: '停用' }
  ]
};

const UnitContext = createContext();

const UnitContextProvider = (props) => {
  const [state, dispatch] = useReducer(UnitReducer, initialState);

  const actions = {
    /**
     * @description: 表格选中的项目
     * @param {*} selectArr 选中的项目
     */
    setSelectedItem(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 增加单位
     * @param {*} params 增加单位的参数
     * @return {*} 增加的单位
     */
    async onAddUnit(params) {
      const res = await addUnit(params);
      const { data } = res;
      message.success('添加成功');
      dispatch({ type: ADD_UNIT, data });
      appActions.setUnitList(insertItem(data, appState.unitList));
      return data;
    },

    /**
     * @description: 删除单位
     * @param {*} data 删除单位的ID
     */
    onDeleteUnit(data) {
      const id = data.join(',');
      deleteUnit(id).then((res) => {
        message.success('删除成功');
        const ids = res.data;
        dispatch({ type: DELETE_UNIT, ids });
        appActions.setUnitList(delItemByIdArray(ids, appState.unitList));
      });
    },

    /**
     * @description: 编辑单位
     * @param {*} params 编辑单位的参数
     */
    onEditUnit(params) {
      return new Promise((resolve, reject) => {
        editUnit(params)
          .then((res) => {
            message.success('编辑成功');
            const { data } = res;
            const { id } = data;
            dispatch({ type: EDIT_UNIT, id, data });
            appActions.setUnitList(editItemById(id, data, appState.unitList));
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 设置单位列表参数
     * @param {*} info 新的参数
     */
    setListQuery(info) {
      dispatch({ type: SET_QUERY, info });
    },

    /**
     * @description: 按页获取单位列表
     */
    async fetchData() {
      dispatch({ type: LOADING });
      try {
        const res = await fetchUnitByPage(state.listQuery);
        const { data } = res;
        dispatch({ type: SET_UNITS_LIST, data });
      } catch (err) {
        dispatch({ type: HIDE_LOADING });
      }
    },

    switchTableType() {
      dispatch({ type: SWITCH_TABLE_TYPE });
    }
  };

  const filters = {
    /**
     * @description: 单位状态过滤器
     * @param {number} code 状态Key
     * @return {string} 状态名
     */
    stateFilter(code) {
      return state.stateList.find((item) => item.id === code)?.name || '-';
    },

    /**
     * @description: 根据id获取单位对象
     * @param {number} id 单位ID
     * @return {IUnit} 匹配的单位
     */
    getUnitById(id) {
      return state.list.find((unit) => unit.id === id) || {};
    }
  };

  useEffect(() => {
    actions.fetchData();
  }, [state.listQuery]);

  return (
    <UnitContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </UnitContext.Provider>
  );
};

export const useUnitContext = () => {
  return useContext(UnitContext);
};

export { UnitContext, UnitContextProvider };
